package cn.itsource.exam.controller;

import cn.itsource.exam.domain.Login;
import cn.itsource.exam.domain.Permission;
import cn.itsource.exam.service.IPermissionService;
import cn.itsource.exam.service.LoginService;
import cn.itsource.exam.util.AjaxResult;
import cn.itsource.exam.util.Md5Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by su on 2020/7/8.
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    private IPermissionService permissionService;
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map map, HttpServletRequest rq, HttpServletResponse rb){
//        SecurityUtils.getSubject();
        Login loginUser = loginService.login(map);
        String name = map.get("name").toString();
        String pwd = map.get("password").toString();
        String password = Md5Helper.MD5(map.get("password").toString());
        if (loginUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (!password.equals(loginUser.getPassword())) {
            return  AjaxResult.error("用户名或密码错误请重新输入！");
        }
        rq.getSession().setAttribute("user",loginUser);
        loginUser.setPassword("");
        String checked = map.get("checked").toString();
        if (checked.equals("true")){
            Cookie c1 = new Cookie("userName",name);
            Cookie c2 = new Cookie("password",pwd);
            c1.setMaxAge(7*24*60*60);
            c2.setMaxAge(7*24*60*60);
            c1.setPath("/");
            c2.setPath("/");
            rb.addCookie(c1);
            rb.addCookie(c2);
        }else{
            Cookie[] cookies = rq.getCookies();
            for (Cookie cookie : cookies){
                if ("userName".equals(cookie.getName())||"password".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    rb.addCookie(cookie);
                }
            }
        }
        //根据用户id联查到对应得菜单
        List<Permission> permissionList = permissionService.getPermissionByUserId(loginUser.getId().toString());
        Map<String,Object> re = new HashMap<String,Object>();
        String uToken = UUID.randomUUID().toString();
        re.put("user",loginUser);
        re.put("permissionList",permissionList);
        rq.getSession().setAttribute(uToken,loginUser);
        re.put("uToken",uToken);
        return AjaxResult.success("登录成功！",re);
    }

}
